package com.cloud.api;

import com.cloud.common.util.MsgCode;
import org.apache.commons.lang3.StringUtils;
import com.cloud.common.util.FileBlockUtil;
import com.cloud.common.util.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


/**
 * 上传文件apis
 * @author mi
 */
@RestController
@RequestMapping(value = "/api")
public class UploadFileController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private FileBlockUtil fileBlockUtil;

	/**
	 * <h2>base64 图片上传<h2/>
	 * @param file 文件  MultipartFile格式
	 * @param pathName 路径
	 * @return r
	 */
	@PostMapping(value = "/uploadFile.do")
	public ResultData uploadFileDo(MultipartFile file,String pathName){
		logger.info("method[uploadPicBase64] : 请求文件存放的路径 {}", pathName);
		try {
			String url =fileBlockUtil.saveToFileBlocks(file,pathName);
			if (StringUtils.equals(MsgCode.ERROR_CODE,url)){
				logger.info("method[uploadFileDo] : 上传文件失败{}", url);
				return ResultData.result(false).setStatus(MsgCode.ERROR).setData(url);
			}else {
				logger.info("method[uploadFileDo] : 上传文件成功url为： {}", url);
				return ResultData.result(true).setStatus(MsgCode.SUCCESS).setData(url);
			}
		} catch (Exception e) {
			logger.error("method[uploadFileDo] : 上传文件失败，失败原因为： {}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setStatus(MsgCode.ERROR);
		}
	}


	/**
	 * <h2>base64 图片上传<h2/>
	 * @param imgBase64Str base64格式
	 * @param pathName 路径
	 * @return r
	 */
	@PostMapping("uploadPicBase64.do")
	public ResultData uploadPicBase64(@RequestParam(required = false) String imgBase64Str,
									  @RequestParam(required = false) String pathName) {
		logger.info("method[uploadPicBase64] : 请求文件存放的路径 {}", pathName);
		logger.info("method[uploadPicBase64] : 请求的base64字符串为 {}", imgBase64Str);
		try {
			//调用方法返回url
			String url = fileBlockUtil.uploadPicByBase64(imgBase64Str, pathName);
			if (StringUtils.equals(MsgCode.ERROR_CODE,url)){
				logger.info("method[uploadPicBase64] : 上传文件失败{}", url);
				return ResultData.result(false).setStatus(MsgCode.ERROR).setData(url);
			}else {
				logger.info("method[uploadPicBase64] : 上传文件成功url为： {}", url);
				return ResultData.result(true).setStatus(MsgCode.SUCCESS).setData(url);
			}

		} catch (Exception e) {
			logger.error("method[uploadPicBase64] : 上传文件失败，失败原因为： {}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setStatus(MsgCode.ERROR);
		}
	}

}
